package com.morningstar.gateway.filter;

import cn.hutool.http.useragent.UserAgent;
import cn.hutool.http.useragent.UserAgentUtil;
import com.morningstar.gateway.utils.IpUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import static com.morningstar.common.constants.HeaderConstants.*;

/**
 * 解析请求信息放入Header 以供后续服务使用
 *
 * @author Admin
 */
@Slf4j
@Component
public class HeaderEnhanceFilter implements GlobalFilter, Ordered {

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        String requestIp = IpUtils.getClientIp(exchange.getRequest());
        String userAgent = exchange.getRequest().getHeaders().getFirst(USER_AGENT);
        UserAgent userAgentInfo = UserAgentUtil.parse(userAgent);
        log.info("请求IP:{},请求浏览器:{},请求操作系统:{}",
                requestIp,
                userAgentInfo.getBrowser().getName(),
                userAgentInfo.getOs());
        ServerHttpRequest request = exchange.getRequest().mutate()
                .header(REQUEST_IP, requestIp)
                .header(REQUEST_BROWSER, userAgentInfo.getBrowser() != null ? userAgentInfo.getBrowser().getName() : "")
                .header(REQUEST_OS, userAgentInfo.getOs() != null ? userAgentInfo.getOs().getName() : "")
                .build();
        return chain.filter(exchange.mutate().request(request).build());
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
